<template>
  <el-dialog
    title="分配角色"
    :visible.sync="showDialog"
    width="50%"
    @close="checkRoleIds=[]"
  >
    <!-- 多选组 是会把 label字段内容放入到v-model绑定的变量里面 -->
    <!-- el-checkbox 标签之间表示显示文本内容，如果标签之间没有内容，会用label字段关联的内容作为展示 -->
    <el-checkbox-group v-model="checkRoleIds">
      <el-checkbox v-for="item in list" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>
    <span slot="footer">
      <el-button @click="showDialog = false">Cancel</el-button>
      <el-button type="primary" @click="assignRoleFn">OK</el-button>
    </span>
  </el-dialog>

</template>
<script>
import { getRoleList } from '@/api/settings'
import { getUserDetailById } from '@/api/user'
import { assignRoles } from '@/api/employees'
export default {
  name: 'AssignRole',
  data() {
    return {
      showDialog: false,
      list: [],
      checkRoleIds: [],
      userId: null
    }
  },
  methods: {
    // 获取角色
    async getRoleList() {
      const res = await getRoleList({ page: 1, pagesize: 1000 })
      this.list = res.rows
    },
    // 获取用户信息
    async getUserInfo(id) {
      this.userId = id
      const res = await getUserDetailById(id)
      this.checkRoleIds = res.roleIds
    },
    // 用户分配角色
    async assignRoleFn() {
      if (this.checkRoleIds.length === 0) return this.$message.warning('请勾选角色')
      // 发请求
      try {
        await assignRoles({
          id: this.userId,
          roleIds: this.checkRoleIds
        })
        this.$message.success('关联成功')
        this.userId = null
        this.showDialog = false
      } catch (error) {
        console.log(error)
        this.$message.error('关联失败')
      }
    }
  }
}
</script>
<style  lang='less' scoped>
</style>
